//
//  LoginViewController.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/9/14.
//

import UIKit
import RxSwift

class LoginViewController: BaseViewController {
    var connectLab: UILabel!
    var closeBtn: UIButton! //关闭按钮
    var logoImgView: UIImageView! //登录logo
    var phoneView: KInputTextField! //账号输入框
    var passwordView: KInputTextField! //密码输入框
    var loginBtn: UIButton!   //登录
    var registerBtn: UIButton! //注册
    var forgetBtn: UIButton!  //忘记密码
    private var errorTip: UILabel = {
        let label = UILabel()
        label.textColor = Theme.redColor
        label.backgroundColor = UIColor.clear
        label.font = UIFont.init(name: Theme.PingFangSCRegular, size: 11)
        label.numberOfLines = 0
        label.lineBreakMode = .byTruncatingTail
        label.textAlignment = .left
        label.isHidden = true
        return label
    }()
    var disBag = DisposeBag()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navBar.isHidden = true
        UserModule.shared.token = ""
        UserModule.shared.isLogined = false
        
        //当前环境lab
        connectLab = UILabel()
        connectLab.textColor = Theme.redColor
        connectLab.backgroundColor = UIColor.clear
        connectLab.font = UIFont.systemFont(ofSize: 14)
        connectLab.numberOfLines = 1
        connectLab.lineBreakMode = .byTruncatingTail
        connectLab.textAlignment = .center
        view.addSubview(connectLab)
        
        let arr = ServerConfig.shared.getServerList()
        let curSiteUrl = ServerConfig.requestUrl()
        let curObj = arr.first(where: {$0.siteUrl == curSiteUrl})
        if curObj != nil {
            connectLab.text = curObj?.name ?? ""
        }
        
        closeBtn = UIButton()
        closeBtn.setup_image(image: UIImage.init(named: "login_close"))
        closeBtn.addTarget(self, action: #selector(closeBtnAction), for: .touchUpInside)
        view.addSubview(closeBtn)
        
        logoImgView = UIImageView()
        logoImgView.image = UIImage.init(named: "title_logo")
        logoImgView.contentMode = .scaleAspectFit
        logoImgView.isUserInteractionEnabled = true 
        view.addSubview(logoImgView)
        
        logoImgView.addTapGestureRecognizer(numberOfTaps: 10) {[weak self] _ in
            self?.changeConnect()
        }
        
        //账号
        phoneView = KInputTextField.init(frame: .zero)
        phoneView.textField.keyboardType = .numberPad
        phoneView.textField.returnKeyType = .done
        phoneView.placeholder = MMLocalizedString("login_please_enter_phone", comment: "请输入手机号码")
        self.view.addSubview(phoneView)
        
        //密码
        passwordView = KInputTextField.init(frame: .zero)
        passwordView.textField.isSecureTextEntry = true
        passwordView.keyboardType = .asciiCapable
        passwordView.textField.returnKeyType = .done
        passwordView.placeholder = MMLocalizedString("login_please_enter_pwd", comment: "请输入密码")
        self.view.addSubview(passwordView)
        self.view.addSubview(self.errorTip)
        
        //登录
        loginBtn = UIButton()
        loginBtn.setup_titleLabel(text: MMLocalizedString("login_login", comment: "登录"))
        loginBtn.setup_titleColor(color: UIColor.white)
        loginBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColor), for: .normal)
        loginBtn.setBackgroundImage(UIImage.image(withColor: Theme.mainColorHighLightColor), for: .highlighted)
        loginBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        loginBtn.layer.cornerRadius = 8
        loginBtn.layer.masksToBounds = true
        loginBtn.addTarget(self, action: #selector(loginBtnAction), for: .touchUpInside)
        view.addSubview(loginBtn)
        
        //注册
        registerBtn = UIButton()
        registerBtn.setup_titleLabel(text: MMLocalizedString("login_regist", comment: "注册"))
        registerBtn.setup_titleColor(color: Theme.titleLabColor)
        registerBtn.setBackgroundImage(UIImage.image(withColor: Theme.whiteColor), for: .normal)
        registerBtn.setBackgroundImage(UIImage.image(withColor: Theme.eColor), for: .highlighted)
        registerBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCMedium, size: 16)
        registerBtn.layer.cornerRadius = 8
        registerBtn.layer.masksToBounds = true
        registerBtn.layer.borderWidth = 1
        registerBtn.layer.borderColor = Theme.tfBorderColor.cgColor
        registerBtn.addTarget(self, action: #selector(registerBtnAction), for: .touchUpInside)
        view.addSubview(registerBtn)
        
        //忘记密码
        forgetBtn = UIButton()
        forgetBtn.setup_titleLabel(text: MMLocalizedString("login_forget_pwd", comment: "忘记密码"))
        forgetBtn.setTitleColor(Theme.placeholderColor, for: .normal)
        forgetBtn.setTitleColor(UIColor(hex: 0x939AA8, alpha: 0.6), for: .highlighted)
        forgetBtn.titleLabel?.font = UIFont.init(name: Theme.PingFangSCRegular, size: 14)
        forgetBtn.addTarget(self, action: #selector(forgetBtnAction), for: .touchUpInside)
        view.addSubview(forgetBtn)
        
        let tempPhone = XTManageCenter.getLocalStringDataValue(aKey: UtilCenter.kAccount)
        self.phoneView.textField.text = tempPhone
        self.addSnpLayout()
        self.bindMVVM()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.view.endEditing(true)
        self.view.resignFirstResponder()
    }
    
    private func addSnpLayout(){
        closeBtn.snp.makeConstraints { make in
            make.width.equalTo(40)
            make.left.equalTo(8)
            make.top.equalTo(IphoneTopArea)
            make.height.equalTo(40)
        }
        
        connectLab.snp.makeConstraints { make in
            make.centerX.equalTo(kScreenWidth/2)
            make.top.equalTo(IphoneTopArea)
            make.width.equalTo(200)
            make.height.equalTo(40)
        }
        
        logoImgView.snp.makeConstraints { make in
            make.centerX.equalTo(kScreenWidth/2)
            make.top.equalTo(NavBarHight + 60)
            make.width.equalTo(169)
            make.height.equalTo(54)
        }
        
        phoneView.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(logoImgView.snp.bottom).offset(40)
            make.height.greaterThanOrEqualTo(54)
        }
        
        passwordView.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(phoneView.snp.bottom).offset(14)
            make.height.greaterThanOrEqualTo(54)
        }
        
        errorTip.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.top.equalTo(passwordView.snp.bottom).offset(5)
            make.right.equalTo(-30)
            make.height.greaterThanOrEqualTo(20)
        }
        
        loginBtn.snp.makeConstraints { make in
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.top.equalTo(passwordView.snp.bottom).offset(80)
            make.height.equalTo(46)
        }
        
        registerBtn.snp.makeConstraints { make in
            make.top.equalTo(loginBtn.snp.bottom).offset(14)
            make.left.equalTo(30)
            make.right.equalTo(-30)
            make.height.equalTo(46)
        }
        
        forgetBtn.titleLabel?.sizeToFit()
        let tempW = forgetBtn.titleLabel?.frame.size.width ?? 0
        forgetBtn.snp.makeConstraints { make in
            make.bottom.equalTo(-IphoneXMarginBottom - 60)
            make.height.equalTo(30)
            make.width.equalTo(tempW)
            make.centerX.equalTo(kScreenWidth/2)
        }
        
    }
    
    private func bindMVVM(){
        //密码回车监听
        passwordView.textField.rx.controlEvent(.editingDidEndOnExit).subscribe {[weak self] _ in
            self?.passwordView.textField.resignFirstResponder()
            //self?.loginRequest()
        }.disposed(by: self.disBag)
    }
    
    ///切换环境
    private func changeConnect(){
        self.phoneView.textField.resignFirstResponder()
        self.phoneView.textField.resignFirstResponder()
        let vc = ChangeConnectViewController()
        vc.modalPresentationStyle = .overFullScreen
        vc.callBack = {[weak self] aName in
            self?.connectLab.text = aName
        }
        self.present(vc, animated: false)
        
    }
    
    ///登录按钮事件
    @objc func loginBtnAction(){
        self.errorTip.isHidden = true
        self.phoneView.textField.resignFirstResponder()
        self.passwordView.textField.resignFirstResponder()
        self.loginRequest()
    }
    
    ///登录请求
    private func loginRequest() {
        if !self.validateData() {
            return
        }
        
        self.view.showLoadingHUDText()
        let param = ["username": (self.phoneView.textField.text ?? "").removeAllSapce,
                     "password": self.passwordView.textField.text ?? "",
                     "type":"1"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.login(param: param), objectType: LoginResModel.self) { data in
            self.view.handleLoading()
            let resultObj = data as! LoginResModel
            guard resultObj.code == "1" else {
                self.errorTip.text = resultObj.msg ?? ""
                self.errorTip.isHidden = false
                self.phoneView.warnText = " "
                self.passwordView.warnText = " "
                //self.view.makeToast(message: resultObj.msg ?? "")
                return
            }
            UserModule.shared.isLogined = true
            UserModule.shared.token = resultObj.data?.token ?? ""
            XTManageCenter.setLocalDataString(aKey: UtilCenter.kAccount, aValue: self.phoneView.textField.text ?? "")
            XTManageCenter.setLocalDataString(aKey: XTManageCenter.userId, aValue: "\(resultObj.data?.member?.id ?? 0)")
            self.view.makeToast(message: MMLocalizedString("login_success", comment: "登录成功"))
            self.perform(#selector(self.handleLoginSuccess), afterDelay: 1.5)
        } error: { err in
            self.view.handleLoading()
            self.view.makeToast(message: err?.domain ?? "")
        }
    }
    
    ///校验输入手机号与密码
    private func validateData() -> Bool {
        var flag = true
        let phone = (self.phoneView.textField.text ?? "").removeAllSapce
        let password = self.passwordView.textField.text ?? ""
        if phone == "" {
            self.phoneView.warnText = MMLocalizedString("login_please_enter_phone", comment: "请输入手机号码")
            flag = false
        } else {
            self.phoneView.warnText = ""
        }
        
        if password == "" {
            self.passwordView.warnText = MMLocalizedString("login_please_enter_pwd", comment: "请输入密码")
            flag = false
        }else{
            self.passwordView.warnText = ""
        }
        return flag
    }
    
    ///成功跳转
    @objc func handleLoginSuccess(){
        XTManageCenter.shared.closeLoginPage()
    }
    
    ///注册
    @objc func registerBtnAction(){
        self.phoneView.textField.resignFirstResponder()
        self.phoneView.textField.resignFirstResponder()
        let vc = RegisterViewController()
        vc.phone = self.phoneView.textField.text ?? ""
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    ///关闭返回Home
    @objc func closeBtnAction(){
        self.phoneView.textField.resignFirstResponder()
        self.phoneView.textField.resignFirstResponder()
        self.dismiss(animated: true)
    }
    
    ///忘记密码
    @objc func forgetBtnAction(){
        let vc = ForgetPasswordViewController()
        vc.phone = self.phoneView.textField.text ?? ""
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}
